package com.xzx.flink.streamapi.transform;

import com.xzx.flink.bean.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.ConnectedStreams;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoMapFunction;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2021-08-24 11:11 下午
 */
public class Transform_07_Connect_CoMap {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> streamSource = env.readTextFile("/Users/xinzhixuan/work/git2/flink1234/flink1.14/src/main/resources/sensor.txt");
        SingleOutputStreamOperator<SensorReading> map = streamSource.map(new MapFunction<String, SensorReading>() {
            @Override
            public SensorReading map(String value) throws Exception {
                String[] split = value.split(" ");
                return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
            }
        });

        DataStreamSource<Integer> streamSource1 = env.fromElements(1, 2, 3, 4);

        ConnectedStreams<SensorReading, Integer> connect = map.connect(streamSource1);
        SingleOutputStreamOperator<Object> result = connect.map(new CoMapFunction<SensorReading, Integer, Object>() {
            // 第一个流
            @Override
            public Object map1(SensorReading value) throws Exception {
                return Tuple3.of(value.getId(), value.getTimestamp(), value.getTemperature());
            }

            // 第二个流
            @Override
            public Object map2(Integer value) throws Exception {
                return Tuple1.of(value);
            }
        });
        result.print();


        env.execute(Transform_07_Connect_CoMap.class.getName());
    }
}
